package com.zeeephr.core;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Date;

import com.zeeephr.core.bean.Conf;

public class Response {

	private StringBuilder sb;
	private StringBuilder contentSb;
	private BufferedWriter bw;
	private final String blank=" ";
	private final String rN="\r\n";
	public Response(OutputStream output) {
		bw=new BufferedWriter(new OutputStreamWriter(output));
		contentSb=new StringBuilder();
		sb=new StringBuilder();
	}
	public Response(BufferedWriter bw) {
		this.bw=bw;
		contentSb=new StringBuilder();
		sb=new StringBuilder();
	}
	public Response print(String str) {
		contentSb.append(str);
		return this;
	}
	
	
	public void SetHead(int code) {
		switch(code) {
		case 200:sb.append("HTTP/1.1").append(blank).append(200).append(blank).append("OK").append(rN);
			break;
		case 404:sb.append("HTTP/1.1").append(blank).append(404).append(blank).append("NOT FOUND").append(rN);
			break;
		case 500:sb.append("HTTP/1.1").append(blank).append(404).append(blank).append("Internal Server Error").append(rN);
			break;
		}
		
	}
	
	public void SetHeadLine() {
		String s=contentSb.toString();
		int byteLen=s.getBytes().length;
		sb.append("Date:").append(new Date()).append(rN);
		sb.append("Server:").append(Server.conf.getName()).append(rN);
		sb.append("Content-type:").append("text/html").append(rN);
		sb.append("Content-length:").append(byteLen).append(rN);
		sb.append(rN);
		sb.append(contentSb.toString());
	}
	public void readHtml(String fileName) throws IOException {
		
		InputStream input=Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
		byte b[]=new byte[1024*1024];
		int len=0;
		input.read(b);
		String str=new String(b,0,len);
		print(str);
	}
	public void sendRedirect(String where) {
		
	}
	public void send(int code){
		
		SetHead(code);
		SetHeadLine();
		
		try {
			bw.write(sb.toString());
			bw.flush();
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
